import { PlusOutlined, ExclamationCircleOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Menu, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import TableForm from './components/TableForm';
import HeaderDropdown from '@/components/HeaderDropdown/index';
import { services } from '@/network/api';
import utils from '@/utils/index';

const { confirm } = Modal;
type formState = {
  visible?: boolean;
  id?: any;
  busType?: any;
};

type col = {
  id: number;
  name: string;
  label: string;
  busType: number;
  fieldType: number;
  isDefault: number;
  isRequire: number;
  isEnable: number;
  describe: string;
  order: number;
  fieldOption: string;
  createDate: string;
};

const tabList = [
  {
    key: '1',
    tab: '用户',
  },
  {
    key: '2',
    tab: '线索',
  },
  {
    key: '3',
    tab: '客户',
  },
];

const TableList: React.FC = (props: any) => {
  const { route } = props;

  const [formState, setFormState] = useState<formState>({
    visible: false,
    id: null,
    busType: 1,
  });
  const [selectedRows, setSelectedRows] = useState<col[]>([]);
  const actionRef = useRef<ActionType>();

  const handleTabChange = (...arg: any) => {
    setFormState({ ...formState, busType: +arg[0] });
  };

  const delFieldList = () => {
    confirm({
      title: '确认删除字段?',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        const delFieldList = async () => {
          await services.delFieldList({
            idList: selectedRows.map((item) => {
              return item.id;
            }),
          });
          setTimeout(() => {
            actionRef?.current?.clearSelected?.();
            actionRef?.current?.reload();
          }, 300);
        };
        delFieldList();
      },
    });
  };

  const columns: ProColumns<col>[] = [
    {
      title: '字段id',
      dataIndex: 'id',
      sorter: true,
    },
    {
      title: '字段标签',
      dataIndex: 'label',
      order: 3,
      sorter: true,
    },
    {
      title: '字段类型',
      dataIndex: 'fieldType',
      valueEnum: utils.constant.FORM_TYPE_LIST.toEnum(),
    },
    {
      title: '是否启用',
      dataIndex: 'isEnable',
      valueEnum: {
        0: {
          text: '停用',
          status: 'Default',
        },
        1: {
          text: '正常',
          status: 'Success',
        },
      },
      sorter: true,
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      valueEnum: {
        0: {
          text: '自定义字段',
        },
        1: {
          text: '默认字段',
        },
      },
      sorter: true,
    },
    {
      title: '是否必填',
      dataIndex: 'isRequire',
      valueEnum: {
        0: {
          text: '否',
        },
        1: {
          text: '是',
        },
      },
      sorter: true,
    },
    {
      title: '描述',
      dataIndex: 'describe',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '创建日期',
      dataIndex: 'createDate',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建日期范围',
      dataIndex: 'createDateRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
    },
    {
      title: '字段顺序',
      dataIndex: 'order',
      hideInSearch: true,
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        route.checkBtn('edit') && (
          <a
            onClick={() => {
              setFormState({ ...formState, visible: true, id: record.id });
            }}
          >
            修改
          </a>
        ),
        route.checkBtn('delete') && (
          <a
            onClick={() => {
              confirm({
                title: '确认删除字段?',
                icon: <ExclamationCircleOutlined />,
                onOk() {
                  const delFieldList = async () => {
                    await services.delFieldList({ idList: [record.id] });
                    setTimeout(() => {
                      actionRef?.current?.reload();
                    }, 300);
                  };
                  delFieldList();
                },
              });
            }}
          >
            删除
          </a>
        ),
        route.checkBtn('option') && (
          <HeaderDropdown
            overlay={
              <Menu selectedKeys={[]}>
                {!!record.isEnable && (
                  <Menu.Item
                    onClick={() => {
                      const saveField = async () => {
                        await services.saveField({ isEnable: 0, id: record.id });
                        setTimeout(() => {
                          actionRef?.current?.reload();
                        }, 300);
                      };
                      saveField();
                    }}
                  >
                    停用
                  </Menu.Item>
                )}
                {!record.isEnable && (
                  <Menu.Item
                    onClick={() => {
                      const saveField = async () => {
                        await services.saveField({ isEnable: 1, id: record.id });
                        setTimeout(() => {
                          actionRef?.current?.reload();
                        }, 300);
                      };
                      saveField();
                    }}
                  >
                    启用
                  </Menu.Item>
                )}
              </Menu>
            }
          >
            <a>
              <EllipsisOutlined />
            </a>
          </HeaderDropdown>
        ),
      ],
    },
  ];

  return (
    <PageContainer
      tabList={tabList}
      tabActiveKey={formState.busType + ''}
      onTabChange={handleTabChange}
    >
      <ProTable
        headerTitle="字段管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolbar={{}}
        columnsState={{
          persistenceType: 'localStorage',
          persistenceKey: 'fieldTableColSet',
        }}
        toolBarRender={() => [
          route.checkBtn('add') && (
            <Button
              type="primary"
              onClick={() => {
                setFormState({ ...formState, visible: true, id: null });
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ),
          route.checkBtn('delete') && (
            <Button type="primary" disabled={!selectedRows?.length} danger onClick={delFieldList}>
              <PlusOutlined /> 批量删除
            </Button>
          ),
        ]}
        params={{ busType: formState.busType }}
        request={async (param, orderParam, ...arg) => {
          return await services.getFieldList({
            ...param,
            orderParam,
            noMsg: true,
            noThrottle: true,
          });
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <TableForm
        {...formState}
        onVisibleChange={(visible) => {
          setFormState({ ...formState, visible });
        }}
        _onFinish={() => {
          setFormState({ ...formState, visible: false });
          setTimeout(() => {
            actionRef?.current?.reload();
          }, 300);
        }}
      />
    </PageContainer>
  );
};

export default TableList;
